$(document).ready(function(){
    var first_cate = $("#first_cate");
    var second_cate = $("#second_cate");
    var third_cate = $("#third_cate");
    
    
    var attr_area_outter = $("#attr-area-outter");
    var publish_submit_button = $("#publish-submit-button");
    var uploadimg_display_outter = $("#uploadimg-display-outter");
    
    
    var install_price_line = $("#install-price-line");
    var areanum_item = $("#areanum-line");
    var order_endtime_line_item = $("#order-endtime-line");
    var is_tall_line_item = $("#is-tall-line");
    var location_line = $("#location-line");
    
    var goods_attr_array = [];
    var goods_img = [];
    
    if(first_cate.val() == 1){
        $("#package").attr('placeholder','入口道闸 500 100 2020-06-18\n出口道闸 300 100 2020-06-18');
        $("#package-description").html('每一行代表一个套餐，格式：套餐名称 价格 每月安装维护费 起售日期，如：入口道闸 500 100 2020-06-18');
    }else{
        $("#package").attr('placeholder','套餐一 500 99\n套餐二 300 99');
        $("#package-description").html('每一行代表一个套餐，格式：套餐名称 价格 库存数量，如：套餐一 500 99');
    }
    
    function init_thirdCate(){
        var firstCate = second_cate.val();
        $params = JSON.stringify({'cate_id':firstCate});
        $third_cate_back = ajaxSynchroRequest("/api/publish/getsubcate",$params);
        var options = '<option value="0">--请选择--</option>';
        $.each($third_cate_back.data,function(index,value){
            options += '<option value="'+value.id+'">'+value.name+'</option>';
       });
       third_cate.empty(); 
       third_cate.append(options);
    }
    
    second_cate.change(function(){ 
        init_thirdCate();
    });
    third_cate.change(function(){ 
        init_attr_input();
    });
    
    function init_attr_input(){
        var thirdCate = third_cate.val();
        $params = JSON.stringify({'cate_id':thirdCate});
        $cate_attr_back = ajaxSynchroRequest("/api/publish/get-attr",$params);
        goods_attr_array = $cate_attr_back.data;
        //console.log($cate_attr_back);
        var html = '';
        $.each($cate_attr_back.data,function(index,value){
            var is_must_font = value.is_must == 1 ? '<span class="must-input">*</span>':'';
            if(value.type == 0){//文本框
                html += '<div class="publish-item-line"><div class="goods_label">'+is_must_font+value.name+'：</div><div class="goods_input_backset" data-name="'+value.name+'" data-must="'+value.is_must+'" data-type="'+value.type+'"><input type="text" name="attr_'+value.id+'" id="attr_'+value.id+'" data-name="'+value.name+'"/></div></div>';
            }
            if(value.type == 1){//单选项
                var option_html = '';
                $.each(value.optional,function(op_index,op_value){
                    option_html += '<option  value="'+op_value.id+'">'+op_value.val+'</option>';
                });
                html += '<div class="publish-item-line"><div class="goods_label">'+is_must_font+value.name+'：</div><div class="goods_input_backset" data-name="'+value.name+'" data-must="'+value.is_must+'" data-type="'+value.type+'"><select name="attr_'+value.id+'" id="attr_'+value.id+'" data-name="'+value.name+'">'+option_html+'</select></div></div>';
            }
            if(value.type == 2){//多选项
                var option_html = '';
                $.each(value.optional,function(op_index,op_value){
                    option_html += '<input class="input-checkbox" id="option_'+op_value.id+'" type="checkbox" name="attr_'+value.id+'[]" id="attr_'+value.id+'" value="'+op_value.id+'"><label for="option_'+op_value.id+'">'+op_value.val+'</label>';
                });
                html += '<div class="publish-item-line"><div class="goods_label">'+is_must_font+value.name+'：</div><div class="goods_input_backset" data-name="'+value.name+'" data-must="'+value.is_must+'" data-type="'+value.type+'">'+option_html+'</div></div>';
            }
        });
        attr_area_outter.empty(); 
        attr_area_outter.append(html);
    }
    

    publish_submit_button.on('click',function(){
        var submit_able = 1;
        var data = {};
        //检测分类是否合法
        if($("#first_cate").val()==0 || $("#second_cate").val()==0 || $("#third_cate").val()==0){
            submit_able = 0;
            layer.msg('请选择商品类型！'); 
            return false;
        }
        //检测商品名称是否合法
        if($("#goodsname").val()==""){
            submit_able = 0;
            layer.msg('请输入商品名称！');
            return false;
        }
        //检测商品名称是否合法
        if($("#install_price").val()=="" && first_cate.val() == 1){
            submit_able = 0;
            layer.msg('请输入安装维护费！');
            return false;
        }
        //检测广告面积是否合法
        if($("#area_num").val()=="" && first_cate.val() == 1){
            submit_able = 0;
            layer.msg('请输入广告面积！');
            return false;
        }
        
        //检测价格
        if($("#price").val()==""){
            submit_able = 0;
            layer.msg('请输入商品价格！');
            return false;
        }
        
        //检测起售时间是否合法
        if($("#order_endtime").val()=="" && first_cate.val() == 1){
            submit_able = 0;
            layer.msg('请选择起售时间！');
            return false;
        }
        
        console.log(goods_attr_array);
        //检测系统定义属性是否合法
        $.each(goods_attr_array,function(index,value){
            if(value.type==='0'){
                if(value.is_must==='1' && $("#attr_"+value.id).val()===""){
                    submit_able = 0;
                    layer.msg('【'+value.name+'】不能为空');
                    return false;
                }
                data['attr_'+value.id] = $("#attr_"+value.id).val();
            }
            if(value.type==='1'){
                if(value.is_must==='1' && $("#attr_"+value.id).val()===""){
                    submit_able = 0;
                    layer.msg('请选择【'+value.name+'】');
                    return false;
                }
                data['attr_'+value.id] = $("#attr_"+value.id).val();
            }
            if(value.type==='2'){
                if(value.is_must==='1' && $("[name = 'attr_"+value.id+"[]']:checked").length===0){
                    submit_able = 0;
                    layer.msg('至少选择一个【'+value.name+'】');
                    return false;
                }
                //var checkbox_val = [];
                var checkbox_val = '';
                $.each($("[name = 'attr_"+value.id+"[]']:checked"),function(){
                    checkbox_val += ','+$(this).val();
                    //checkbox_val.push($(this).val());
                });
                checkbox_val = checkbox_val.substring(1)
                data['attr_'+value.id] = checkbox_val;
            }
        });
        //console.log(data);return false;
        
        //检测图片
        var uploadimg_display = $(".uploadimg-display");
        if(uploadimg_display.length == 0){
            submit_able = 0;
            layer.msg('至少要上传一张图片');
            return false;
        }
        
        for(var j=0;j<uploadimg_display.length;j++){
            //var img_input_html = '<input type="hidden" name="goodsimg_'+j+'" value="'+uploadimg_display[j].attributes[0].nodeValue+'"/>';
            data['goodsimg_'+j] = uploadimg_display[j].attributes[0].nodeValue;
        }
		
        var longitude =  $("#longitude").val();
        if(longitude == '' && (first_cate.val()==1 || first_cate.val()==8)){
            submit_able = 0;
            layer.msg('请选择位置');
            return false;
        }
        var latitude = $("#latitude").val();
        var region_area = $("#region_area").val();
        var address = $("#address").val();
        if(latitude == '' && (first_cate.val()==1 || first_cate.val()==8)){
            submit_able = 0;
            layer.msg('请选择位置');
            return false;
        }
        if(first_cate.val()==1 || first_cate.val()==8){
            data['longitude'] = longitude;
            data['latitude'] = latitude;
            data['region_area'] = region_area;
            data['address'] = address;
        }
        
        if(submit_able===1){
            var have_package = $("#have_package").val();
            if(have_package == 1){
                var package = $("#package").val();
                data['package'] = package;
            }
            
            data['first_cate'] = $("#first_cate").val();
            data['second_cate'] = $("#second_cate").val();
            data['third_cate'] = $("#third_cate").val();
            data['goodsname'] = $("#goodsname").val();
            data['price'] = $("#price").val();
            data['install_price'] = $("#install_price").val();
            
            data['have_package'] = have_package;
            data['area_num'] = $("#area_num").val();
            data['is_tall'] = $("#is_tall").val();
            data['order_endtime'] = $("#order_endtime").val();
            
            $params = JSON.stringify(data);
            console.log($params);
            
            $goods_save_back = ajaxSynchroPostRequest("/api/publish/save",$params);
            console.log($goods_save_back);
            if($goods_save_back.success == 1){
                layer.open({
                    content: $goods_save_back.msg,
                    skin: 'msg',
                    time: 3000 //3秒后自动关闭
                });
                window.location.href='/user/goodslist';
            }else{
                layer.open({
                    content: $goods_save_back.msg,
                    skin: 'msg',
                    time: 3000 //3秒后自动关闭
                });
            }
        }
    });
    
    
    $("#uploadimg-display-outter").on('click','.uploadeimg-remove',function(){
        $(this).parent().parent().remove();
    });
    
    $('#have_package').on('change',function(){
        if($(this).val() == 0){
            $('#price').removeAttr("disabled");
            $('#package').val('');
            $('#package-area-outter').hide();
        }else{
            $('#price').val(0);
            $('#price').attr("disabled","disabled");
            $('#package-area-outter').show();
        }
    });
    
    $('#goodsimg-upload').on('change',function(){
        var inputFile = document.getElementById('goodsimg-upload');
        var old_nums = $(".uploadimg-display").length;
        if(inputFile.files.length+old_nums>6){
            layer.open({
                content: '最多能上传6张图片',
                skin: 'msg',
                time: 3000 //3秒后自动关闭
            });
            return false;
        }
        
        for(var i = 0; i<inputFile.files.length ;i++){
            var fr = new FileReader(); // 这个FileReader应该对应于每一个读取的文件都需要重新new一个
            var files = inputFile.files[i]; // files可以获取当前文件输入框中选择的所有文件，返回列表
            fr.readAsDataURL(files); // 读取的内容是加密以后的本地文件路径
            fr.onload = function(e){ // 数据读取完成时触发onload对应的响应函数
                $params = JSON.stringify({'imgdata':e.target.result});
                $cate_attr_back = ajaxSynchroPostRequest("/api/publish/goodsimgupload",$params);
                console.log($cate_attr_back);
                if($cate_attr_back.success==1){
                    uploadimg_display_outter.prepend('<div class="uploadimg-result-single"><img src="'+$cate_attr_back.url+'" data-url="'+$cate_attr_back.url+'" class="uploadimg-display"><div class="remove-outter"><span class="uploadeimg-remove">移除</span></div></div>');
                }
            }
        }
    });
});
